<template>
  <div>
    <el-upload class="upload-demo" v-model:file-list="fileList" action="" multiple :drag="false" :auto-upload="true"
      :show-file-list="true" :http-request="handleUpLoad" :on-success="handleSuccess" :on-error="handleError"
      :on-remove="handleRemove" :on-progress="handleProgress">
      <el-button class="upload-btn" :type="initConfig.type" :plain="initConfig.plain" size="small">{{ initConfig.btnText
        }}</el-button>

      <template #tip v-if="initConfigData.tipText !== ''">
        <div class="el-upload__tip text-gray-500 text-xs">
          {{ initConfigData.tipText }}
        </div>
        <!-- <div class="el-upload__tip text-gray-500 text-xs">
          支持上传多个文件，单个文件不超过50MB
        </div> -->
      </template>

      <!-- 添加进度条显示区域 -->
      <template #file="{ file }">
        <div class="upload-progress-container">
          <div class="file-progress">
            <div class="file-name">
              <p>{{ file.name }}</p>
              <el-progress style="width: calc(100% - 50px);margin-top: 4px;" v-if="file.status === 'uploading'"
                :percentage="file.percentage" :stroke-width="2"
                :status="file.status === 'exception' ? 'exception' : ''" />
            </div>
            <!-- <div>{{ file }}</div> -->
          </div>
          <div class="file-icon">
            <el-icon v-if="file.status === 'ready' || file.status === 'uploading'" color="#409EFF">
              <Loading />
            </el-icon>
            <el-icon v-if="file.status === 'success'" color="#67C23A">
              <CircleCheck />
            </el-icon>
            <el-icon v-if="file.status === 'exception'" color="#F56C6C">
              <CircleCheck />
            </el-icon>
            <el-icon v-if="file.status === 'success' || file.status === 'exception'" color="#F56C6C"
              @click.stop="handleRemove(file)">
              <Delete />
            </el-icon>
          </div>
        </div>
      </template>
    </el-upload>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, PropType, watch, } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";


const fileList = ref<any>([]);//已上传的附件
const filePaths = ref<any>([]);//所有上传文件响应地址
const filePath = ref<any>("");// 当次上传文件地址

const initConfigData = ref<any>();// 初始配置项
const resetFields = ref(false);// 是否重置文件列表

const props = defineProps({
  initConfig: {
    type: Object as PropType<any>,
    required: true,
    default: () => ({
      tipText: "",
      type: "primary",
      plain: true,
      btnText: "上传",
      fileUrl: "/file/upload_file",
      fileType: "",
      fileTypeId: "5",
    })
  },
  resetFiles: {
    type: Boolean,
    required: true,
  }
});

const emit = defineEmits(['updateFilePaths']);

watch(() => props.initConfig, (newInitConfig) => {
  console.log(newInitConfig);
  if (newInitConfig) {
    initConfigData.value = newInitConfig;
    fileList.value = [];
    filePaths.value = [];
    filePath.value = "";
  }
}, { immediate: true });

watch(() => props.resetFiles, (newResetFiles) => {
  console.log(newResetFiles);
  if (newResetFiles) {
    resetFields.value = newResetFiles;
    fileList.value = [];
    filePaths.value = [];
    filePath.value = "";
  }
}, { immediate: true });

// TODO 自定义上传文件
const handleUpLoad = async (options: any) => {
  console.log("Options:", options);
  try {
    const { file } = options;
    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileType', `${initConfigData.value.fileType}`);
    formData.append('fileTypeId', `${initConfigData.value.fileTypeId}`);

    // 假设你的 postUploadFile 支持进度回调
    const response = await request.post(initConfigData.value.fileUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'token': localStorage.getItem("TOKEN")
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          options.onProgress({
            percent: Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            )
          })
        }
      }
    });

    if (response.data.code === 200) {
      options.onSuccess(response);
    } else {
      options.onError("上传失败");
    }


  } catch (error) {
    ElMessage.error('上传失败');
    options.onError(error);
  }
};


const handleSuccess = (response: any, uploadFile: any, fileList: any) => {

  if (!response || !response.data) {
    console.error("Invalid response:", response);
    return; // 避免后续操作
  };

  if (response.data.code === 200) {

    const fileRes = response.data.data.resultFilePath;
    // 更新文件列表显示
    uploadFile.url = fileRes; // 设置文件URL以便显示
    uploadFile.name = uploadFile.name || fileRes.split('/').pop(); // 设置文件名

    filePath.value = fileRes;
    filePaths.value.unshift(fileRes);

    emit('updateFilePaths', filePaths.value);

    ElMessage.success('文件上传成功');
  } else {
    const index = fileList.indexOf(uploadFile.url);
    if (index !== -1) {
      fileList.splice(index, 1);
    }
    ElMessage.error("上传失败");
  }

};

const handleError = (err: any) => {
  ElMessage.error(err);
};

const handleRemove = (file: any) => {

  // fileList.value = fileList.value.filter((item: any) => item.name !== v.name);
  // filePaths.value = filePaths.value.filter((path: any) => path.fileName !== v.name);
  const index = fileList.value.indexOf(file);
  if (index !== -1) {
    fileList.value.splice(index, 1);
    filePaths.value = fileList.value.map((item: any) => item.url);
    ElMessage.success('文件已删除');
    emit('updateFilePaths', filePaths.value);
  }
};

const handleProgress = (progress: any) => {
};

</script>

<style lang='scss' scoped>
// 文件列表样式
.upload-progress-container {
  width: calc(100% - 10px);
  height: 28px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  border: 1px solid #409EFF;
  border-radius: 5px;
  padding: 0 5px;

  .file-progress {
    width: calc(100% - 40px);
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    margin-right: 5px;

    .file-progress-status {
      width: calc(100% - 60px);
      font-size: 10px;
    }

    .file-name {
      width: 100%;
      p {
        width: 100%;
        // text-overflow: ellipsis;
        // overflow: hidden;        
        white-space: nowrap;
        padding-right: 10px;
        overflow-x: auto;
      }
    }

  }

  .file-icon {
    width: 40px;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-evenly;
    align-items: center;
    margin-left: 5px;
  }
}
</style>